package com.market.goods.service.impl;

import com.market.goods.dao.es.CategoryBrandDocument;
import com.market.goods.service.CategoryBrandService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CategoryBrandServiceImpl implements CategoryBrandService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public List<CategoryBrandDocument> inputAndSearch(String queryWorld) {
        log.info("inputAndSearch={}", queryWorld);
        MatchPhrasePrefixQueryBuilder matchPhrasePrefixQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("brandName", queryWorld);
        matchPhrasePrefixQueryBuilder.maxExpansions(10);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置查询，可以是任何类型的QueryBuilder。
        sourceBuilder.query(matchPhrasePrefixQueryBuilder);
        //设置确定结果要从哪个索引开始搜索的from选项，默认为0
        sourceBuilder.from(0);
        //设置确定搜素命中返回数的size选项，默认为10
        sourceBuilder.size(20);
        //设置一个可选的超时，控制允许搜索的时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//        sourceBuilder.fetchSource(new String[] {"fields.port","fields.entity_id","fields.message"}, new String[] {}); //第一个是获取字段，第二个是过滤的字段，默认获取全部
        SearchRequest searchRequest = new SearchRequest("category_brand"); //索引
//        searchRequest.types("doc"); //类型
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("inputAndSearchError={}",e);
        }
        SearchHits hits = response.getHits();  //SearchHits提供有关所有匹配的全局信息，例如总命中数或最高分数：
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            log.info("search -> {}", hit.getSourceAsString());
        }
        return null;
    }
}
